<template>
    <div>
        <!-- 检查更新弹框 -->
        <a-modal
            v-model="updateCheckVisible"
            title="检查更新"
            :footer="null"
            :closable="false"
            :mask-closable="false"
            centered
        >
            <div style="text-align: center;">
                <a-spin size="large" />
                <p style="margin-top: 16px;">正在检查更新，请稍候...</p>
            </div>
        </a-modal>

        <!-- 更新确认弹框 -->
        <a-modal
            v-model="updateConfirmVisible"
            title="发现新版本"
            ok-text="立即更新"
            cancel-text="稍后更新"
            @ok="handleUpdateConfirm"
            @cancel="updateConfirmVisible = false"
        >
            <div>
                <p>发现新版本：{{ latestVersion }}</p>
                <p>是否立即更新？</p>
            </div>
        </a-modal>

        <!-- 错误提示弹框 -->
        <a-modal
            v-model="updateErrorVisible"
            title="检查更新失败"
            ok-text="确定"
            :cancel-button-props="{ style: { display: 'none' } }"
            @ok="updateErrorVisible = false"
        >
            <p>{{ errorMessage }}</p>
        </a-modal>

        <!-- 版本信息弹框 -->
        <a-modal
            v-model="versionInfoVisible"
            title="版本信息"
            :footer="null"
            width="500px"
            centered
        >
            <div v-if="versionInfoLoading" style="text-align: center; padding: 20px;">
                <a-spin size="large" />
                <p style="margin-top: 16px;">正在获取版本信息...</p>
            </div>
            <div v-else-if="versionInfo">
                <a-descriptions :column="1" bordered>
                    <a-descriptions-item label="当前版本">
                        {{ versionInfo.currentVersion }}
                    </a-descriptions-item>
                    <a-descriptions-item label="最新版本">
                        {{ versionInfo.latestVersion }}
                    </a-descriptions-item>
                    <!-- <a-descriptions-item label="发布时间">
                        {{ versionInfo.releaseDate }}
                    </a-descriptions-item> -->
                    <a-descriptions-item v-if="versionInfo.releaseNotes" label="更新内容">
                        <div style="max-height: 200px; overflow-y: auto;">
                            <pre style="white-space: pre-wrap; font-family: inherit;">{{
                versionInfo.releaseNotes
                            }}</pre>
                        </div>
                    </a-descriptions-item>
                </a-descriptions>

                <div style="text-align: center; margin-top: 20px;">
                    <a-button
                        v-if="versionInfo.hasUpdate"
                        type="primary"
                        style="margin-right: 8px;"
                        @click="handleVersionInfoUpdate"
                    >
                        立即更新
                    </a-button>
                    <a-button @click="versionInfoVisible = false"> 关闭 </a-button>
                </div>
            </div>
            <div v-else style="text-align: center; padding: 20px;">
                <a-icon
                    type="exclamation-circle"
                    style="font-size: 48px; color: #faad14;"
                />
                <p style="margin-top: 16px;">获取版本信息失败</p>
                <a-button
                    type="primary"
                    style="margin-right: 8px;"
                    @click="getVersionInfo"
                >
                    重试
                </a-button>
                <a-button @click="versionInfoVisible = false"> 关闭 </a-button>
            </div>
        </a-modal>
    </div>
</template>

<script>
import cefsharpAdapter from '../../api/cefsharp'

export default {
    name: 'UpdateManager',
    data() {
        return {
            updateCheckVisible: false,
            updateConfirmVisible: false,
            updateErrorVisible: false,
            versionInfoVisible: false,
            versionInfoLoading: false,
            latestVersion: '',
            errorMessage: '',
            updateResult: null,
            versionInfo: null
        }
    },
    methods: {
        async checkForUpdates() {
            // 显示正在检查更新的弹框
            this.updateCheckVisible = true

            try {
                const currentVersion = '0.0.0'

                // 使用cefsharpAdapter调用原生接口检查更新
                if (cefsharpAdapter.checkEnvironment()) {
                    // 创建超时Promise
                    const timeoutPromise = new Promise((_, reject) => {
                        setTimeout(() => {
                            reject(new Error('检查更新超时，请检查网络连接后重试'))
                        }, 30000) // 30秒超时
                    })

                    // 使用Promise.race来实现超时控制
                    const result = await Promise.race([
                        cefsharpAdapter.callNativeMethod('CheckForUpdates', {
                            currentVersion
                        }),
                        timeoutPromise
                    ])
                    console.log('Update check result:', result)
                    // 关闭检查弹框
                    this.updateCheckVisible = false
                } else {
                    // 如果CefSharp不可用，使用原有的emit方式
                    this.updateCheckVisible = false
                    this.$emit('check-update', { currentVersion })
                }
            } catch (error) {
                // 关闭加载弹框
                this.updateCheckVisible = false

                // 显示错误信息
                this.showError(error.message || '检查更新时发生错误，请稍后重试')

                // 向父组件发送错误事件
                this.$emit('check-update', {
                    currentVersion: null,
                    error: error.message
                })
            }
        },

        handleUpdateConfirm() {
            this.updateConfirmVisible = false
            this.$emit('start-update', this.updateResult)
        },

        showError(message) {
            this.errorMessage = message
            this.updateErrorVisible = true
        },

        // 显示版本信息弹框
        async showVersionInfo() {
            this.versionInfoVisible = true
            await this.getVersionInfo()
        },

        // 获取版本信息
        async getVersionInfo() {
            this.versionInfoLoading = true
            this.versionInfo = null

            try {
                // 使用cefsharpAdapter调用原生接口获取版本信息
                if (cefsharpAdapter.checkEnvironment()) {
                    // 创建超时Promise
                    const timeoutPromise = new Promise((_, reject) => {
                        setTimeout(() => {
                            reject(new Error('获取版本信息超时，请检查网络连接后重试'))
                        }, 15000) // 15秒超时
                    })

                    // 使用Promise.race来实现超时控制
                    const result = await Promise.race([
                        cefsharpAdapter.callNativeMethod('GetVersionInfo'),
                        timeoutPromise
                    ])

                    console.log('Version info result:', result)
                    
                    const data = JSON.parse(result.data)
                    if (result.code === 0) {
                        this.versionInfo = {
                            currentVersion: data.currentVersion || '0.0.0',
                            latestVersion: data.latestVersion || '0.0.0',
                            releaseNotes: data.changeLog || '',
                            hasUpdate: data.hasUpdate || false
                        }
                    } else {
                        console.error('获取版本信息失败:', result.msg)
                        this.versionInfo = null
                    }
                } else {
                    // 如果CefSharp不可用，显示默认信息
                    this.versionInfo = {
                        currentVersion: '0.0.0',
                        latestVersion: '未知',
                        releaseDate: '未知',
                        releaseNotes: 'CefSharp环境不可用，无法获取版本信息',
                        hasUpdate: false
                    }
                }
            } catch (error) {
                console.error('获取版本信息异常:', error)
                this.versionInfo = null
            } finally {
                this.versionInfoLoading = false
            }
        },

        // 从版本信息弹框触发更新
        handleVersionInfoUpdate() {
            this.versionInfoVisible = false
            // 如果有版本信息且需要更新，直接触发更新
            if (this.versionInfo && this.versionInfo.hasUpdate) {
                this.checkForUpdates()
            }
        },

        // 重置所有状态
        reset() {
            this.updateCheckVisible = false
            this.updateConfirmVisible = false
            this.updateErrorVisible = false
            this.versionInfoVisible = false
            this.versionInfoLoading = false
            this.latestVersion = ''
            this.errorMessage = ''
            this.updateResult = null
            this.versionInfo = null
        }
    }
}
</script>